<template>
  <div class="dashboard">
    <section class="dashboard-hero">
      <div class="dashboard-hero__text">
        <span class="dashboard-hero__eyebrow">管理员门户</span>
        <h2 class="dashboard-hero__title">您好，{{ userName }}</h2>
        <p class="dashboard-hero__desc">
          统筹全局排课与权限管理，守护平台稳定运行，打造高效协同的教学管理体验。
        </p>
        <div class="dashboard-hero__meta" v-if="heroChips.length">
          <span v-for="chip in heroChips" :key="chip" class="dashboard-chip">{{ chip }}</span>
        </div>
      </div>
      <div class="dashboard-hero__badge">
        <el-icon><Setting /></el-icon>
      </div>
    </section>

    <el-card class="dashboard-card" shadow="hover">
      <template #header>
        管理员信息
      </template>
      <div class="info-grid">
        <div v-for="item in profileItems" :key="item.label" class="info-grid__item">
          <span class="info-grid__label">{{ item.label }}</span>
          <span class="info-grid__value">{{ item.value }}</span>
        </div>
      </div>
    </el-card>

    <!-- 统计数据 -->
    <div class="stats-grid">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon student">
            <el-icon size="40"><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.studentCount }}</div>
            <div class="stat-label">学生总数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon teacher">
            <el-icon size="40"><Avatar /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.teacherCount }}</div>
            <div class="stat-label">教师总数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon clazz">
            <el-icon size="40"><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.clazzCount }}</div>
            <div class="stat-label">班级总数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon course">
            <el-icon size="40"><Reading /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.courseCount }}</div>
            <div class="stat-label">课程总数</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 快速操作 -->
    <el-card class="dashboard-card" shadow="hover">
      <template #header>
        快速操作
      </template>
      <div class="action-grid">
        <div class="action-item" @click="navigateTo('student')">
          <el-icon size="32" color="#409EFF"><User /></el-icon>
          <span>学生管理</span>
        </div>
        <div class="action-item" @click="navigateTo('teacher')">
          <el-icon size="32" color="#67C23A"><Avatar /></el-icon>
          <span>教师管理</span>
        </div>
        <div class="action-item" @click="navigateTo('clazz')">
          <el-icon size="32" color="#E6A23C"><User /></el-icon>
          <span>班级管理</span>
        </div>
        <div class="action-item" @click="navigateTo('course')">
          <el-icon size="32" color="#F56C6C"><Reading /></el-icon>
          <span>课程管理</span>
        </div>
        <div class="action-item" @click="navigateTo('schedule')">
          <el-icon size="32" color="#9C27B0"><Calendar /></el-icon>
          <span>排课管理</span>
        </div>
        <div class="action-item" @click="navigateTo('schedule-statistics')">
          <el-icon size="32" color="#FF9800"><TrendCharts /></el-icon>
          <span>排课统计</span>
        </div>
        <div class="action-item" @click="navigateTo('admin')">
          <el-icon size="32" color="#909399"><Setting /></el-icon>
          <span>管理员管理</span>
        </div>
      </div>
    </el-card>

    <!-- 今日统计 -->
    <el-card class="dashboard-card" shadow="hover">
      <template #header>
        今日统计
      </template>
      <div class="today-stats">
        <div class="today-stat-item">
          <span class="today-stat-label">新增学生</span>
          <span class="today-stat-value">{{ todayStats.newStudents }}</span>
        </div>
        <div class="today-stat-item">
          <span class="today-stat-label">新增教师</span>
          <span class="today-stat-value">{{ todayStats.newTeachers }}</span>
        </div>
        <div class="today-stat-item">
          <span class="today-stat-label">活跃课程</span>
          <span class="today-stat-value">{{ todayStats.activeCourses }}</span>
        </div>
        <div class="today-stat-item">
          <span class="today-stat-label">系统使用率</span>
          <span class="today-stat-value">{{ todayStats.systemUsage }}%</span>
        </div>
      </div>
    </el-card>

  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { Setting, User, Reading, Avatar, Calendar, TrendCharts } from '@element-plus/icons-vue'
import { getSystemStats } from '../api/admin'
import { ElMessage } from 'element-plus'

// 定义emit（defineEmits是编译器宏，无需导入）
const emit = defineEmits(['changePage'])

const user = JSON.parse(localStorage.getItem('user') || '{}')

const userName = computed(() => user?.adminName || '管理员')

const roleText = (role) => {
  if (role === 'super_admin') return '超级管理员'
  if (role === 'admin') return '管理员'
  return role || '未分配'
}

const statusText = (status) => {
  if (status === 1) return '启用'
  if (status === 0) return '禁用'
  return status ?? '未设置'
}

const heroChips = computed(() => {
  const chips = []
  if (user?.adminRole) chips.push(`角色 · ${roleText(user.adminRole)}`)
  if (user?.adminNo) chips.push(`编号 · ${user.adminNo}`)
  if (user?.adminPhone) chips.push(`联系电话 · ${user.adminPhone}`)
  return chips
})

const profileItems = computed(() => [
  { label: '管理员编号', value: user?.adminNo || '-' },
  { label: '姓名', value: user?.adminName || '-' },
  { label: '角色', value: roleText(user?.adminRole) },
  { label: '手机号', value: user?.adminPhone || '-' },
  { label: '邮箱', value: user?.adminEmail || '-' },
  { label: '状态', value: statusText(user?.adminStatus) }
])

// 统计数据
const stats = ref({
  studentCount: 0,
  teacherCount: 0,
  clazzCount: 0,
  courseCount: 0
})

// 今日统计
const todayStats = ref({
  newStudents: 0,
  newTeachers: 0,
  activeCourses: 0,
  systemUsage: 85
})

// 获取统计数据
const fetchStats = async () => {
  try {
    console.log('🔍 正在获取系统统计数据...')
    const response = await getSystemStats()
    
    if (response && response.data) {
      console.log('✅ 统计数据获取成功:', response.data)
      
      // 总体统计
      stats.value = {
        studentCount: response.data.studentCount || 0,
        teacherCount: response.data.teacherCount || 0,
        clazzCount: response.data.clazzCount || 0,
        courseCount: response.data.courseCount || 0
      }
      
      // 今日统计
      if (response.data.todayStats) {
        todayStats.value = {
          newStudents: response.data.todayStats.newStudents || 0,
          newTeachers: response.data.todayStats.newTeachers || 0,
          activeCourses: response.data.todayStats.activeCourses || 0,
          systemUsage: response.data.todayStats.systemUsage || 85
        }
      }
    } else {
      console.warn('⚠️ 统计数据格式错误')
      ElMessage.warning('获取统计数据失败')
    }
  } catch (error) {
    console.error('❌ 获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败: ' + (error.message || ''))
  }
}

// 页面跳转
const navigateTo = (page) => {
  console.log('🚀 快速操作 - 跳转到:', page)
  
  // 页面名称映射（与App.vue中的currentPage值对应）
  const pageMap = {
    'student': 'student',                // 学生管理
    'teacher': 'teacher',                // 教师管理
    'clazz': 'clazz',                    // 班级管理
    'course': 'course',                  // 课程管理
    'schedule': 'schedule',              // 排课管理
    'schedule-statistics': 'schedule-statistics', // 排课统计
    'admin': 'admin'                     // 管理员管理
  }
  
  const targetPage = pageMap[page]
  
  if (targetPage) {
    console.log('✅ 发射changePage事件:', targetPage)
    // 发射changePage事件给父组件（App.vue）
    emit('changePage', targetPage)
  } else {
    console.warn('⚠️ 未找到对应页面:', page)
    ElMessage.warning('页面未找到')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStats()
})
</script>

<style scoped>
.dashboard {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.dashboard-hero {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.dashboard-hero__text {
  flex: 1;
}

.dashboard-hero__eyebrow {
  font-size: 14px;
  opacity: 0.9;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.dashboard-hero__title {
  font-size: 32px;
  font-weight: 700;
  margin: 8px 0 16px 0;
}

.dashboard-hero__desc {
  font-size: 16px;
  opacity: 0.9;
  line-height: 1.6;
  margin: 0 0 20px 0;
}

.dashboard-hero__meta {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.dashboard-chip {
  background: rgba(255, 255, 255, 0.2);
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  backdrop-filter: blur(10px);
}

.dashboard-hero__badge {
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  backdrop-filter: blur(10px);
}

.dashboard-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  overflow: hidden;
}

.dashboard-card :deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: 600;
  color: #495057;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.info-grid__item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-grid__label {
  font-size: 12px;
  color: #6c757d;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.info-grid__value {
  font-size: 16px;
  font-weight: 600;
  color: #212529;
}

/* 统计数据样式 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stat-icon.student {
  background: linear-gradient(135deg, #409EFF, #67C23A);
  color: white;
}

.stat-icon.teacher {
  background: linear-gradient(135deg, #67C23A, #E6A23C);
  color: white;
}

.stat-icon.clazz {
  background: linear-gradient(135deg, #E6A23C, #F56C6C);
  color: white;
}

.stat-icon.course {
  background: linear-gradient(135deg, #F56C6C, #909399);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6c757d;
  font-weight: 500;
}

/* 快速操作样式 */
.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 20px;
  padding: 20px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
}

.action-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-item span {
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

/* 今日统计样式 */
.today-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 20px;
  padding: 20px;
}

.today-stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.today-stat-label {
  font-size: 12px;
  color: #6c757d;
  font-weight: 500;
}

.today-stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
}
</style>



